import React, { useState, useEffect, useCallback } from 'react'

export default function UseCallbackDemo () {
  console.log('---UseCallbackDemo---')

  const [count, setCount] = useState(0)
  const [age, setAge] = useState(0)

  // 这种写法，随着模型的改变，会反复定义
  //   const clickMe = () => {
  //     console.log('---count---', count)
  //   }

  // 回调函数，只有在 count 发生改变的时候，才会定义
  const clickMe = useCallback(() => {
    console.log('---count---', count)
  }, [count])

  useEffect(() => {
    // 开启定时器，去更改模型
    const timer1 = setInterval(() => {
      setCount(count => count + 1)
    }, 2000)

    const timer2 = setInterval(() => {
      setAge(age => age + 1)
    }, 500)

    return () => {
      clearInterval(timer1)
      clearInterval(timer2)
    }
  }, [])

  return (
    <div>
      UseCallbackDemo
      <p>count is {count}</p>
      <p>age is {age}</p>
      <p>
        <button onClick={clickMe}>执行某个方法</button>
      </p>
    </div>
  )
}
